package com.yuedou.jylt.facelib.core.utils;

import android.content.Context;
import android.os.Environment;

import com.yuedou.jylt.utils.CPUUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.UUID;

public class DeviceUtil {
    private static final String CACHE_IMAGE_DIR = "aray/cache/devices";
    private static final String DEVICES_FILE_NAME = ".DEVICES";
    
    public static String getDeviceId(final Context context) {
        String deviceId = readDeviceID(context);
        final StringBuffer s = new StringBuffer();
        if (deviceId != null && !"".equals(deviceId)) {
            return deviceId;
        }
        try {
            deviceId = getIMIEStatus(context);
            s.append(deviceId);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        try {
            deviceId = getLocalMac(context).replace(":", "");
            s.append(deviceId);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        if (s == null || s.length() <= 0) {
            final UUID uuid = UUID.randomUUID();
            deviceId = uuid.toString().replace("-", "");
            s.append(deviceId);
        }
        final String md5 = getMD5(s.toString(), false);
        if (s.length() > 0) {
            saveDeviceID(md5, context);
        }
        return md5;
    }
    
    public static String readDeviceID(final Context context) {
        final File file = getDevicesDir(context);
        final StringBuffer buffer = new StringBuffer();
        try {
            if(file!= null){
                final FileInputStream fis = new FileInputStream(file);
                final InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                final Reader in = new BufferedReader(isr);
                int i;
                while ((i = in.read()) > -1) {
                    buffer.append((char)i);
                }
                in.close();
                return buffer.toString();
            }
            return null;
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private static String getIMIEStatus(final Context context) {
//        final TelephonyManager tm = (TelephonyManager)context.getSystemService("phone");
        final String deviceId = CPUUtil.getDeviceId(context);// tm.getDeviceId();
        return deviceId;
    }
    
    private static String getLocalMac(final Context context) {
        String macAddress = null;
        final StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "";
            }
            final byte[] hardwareAddress;
            final byte[] addr = hardwareAddress = networkInterface.getHardwareAddress();
            for (final byte b : hardwareAddress) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        }
        catch (SocketException e) {
            e.printStackTrace();
            return "";
        }
        return macAddress;
    }
    
    public static void saveDeviceID(final String str, final Context context) {
        final File file = getDevicesDir(context);
        try {
            final FileOutputStream fos = new FileOutputStream(file);
            final Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(str);
            out.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getMD5(final String message, final boolean upperCase) {
        String md5str = "";
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final byte[] input = message.getBytes();
            final byte[] buff = md.digest(input);
            md5str = bytesToHex(buff, upperCase);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }
    
    public static String bytesToHex(final byte[] bytes, final boolean upperCase) {
        final StringBuffer md5str = new StringBuffer();
        for (int i = 0; i < bytes.length; ++i) {
            int digital = bytes[i];
            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        if (upperCase) {
            return md5str.toString().toUpperCase();
        }
        return md5str.toString().toLowerCase();
    }
    
    private static File getDevicesDir(final Context context) {
        File mCropFile = null;
        if (Environment.getExternalStorageState().equals("mounted")) {
            final File cropdir = new File(Environment.getExternalStorageDirectory(), "aray/cache/devices");
            if (!cropdir.exists()) {
                cropdir.mkdirs();
            }
            mCropFile = new File(cropdir, ".DEVICES");
        }
        else {
            final File cropdir = new File(context.getFilesDir(), "aray/cache/devices");
            if (!cropdir.exists()) {
                cropdir.mkdirs();
            }
            mCropFile = new File(cropdir, ".DEVICES");
        }
        return mCropFile;
    }
}
